import { builtinModules, createRequire } from 'node:module';
import { execSync } from 'node:child_process';

import { babel } from '@rollup/plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
import terser from '@rollup/plugin-terser';
import json from '@rollup/plugin-json';
import replace from '@rollup/plugin-replace';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import url from '@rollup/plugin-url';

import entryManifest from './plugins/entryManifest.mjs';
const require = createRequire(import.meta.url);
const pkg = require('./package.json');

const buildId = process.env.BUILD_ID || execSync('git rev-parse --short HEAD').toString().trim();

const manifest = entryManifest();

const client = ['main', 'browse'].map(entryName => {
  return {
    external: ['@emotion/react', 'react', 'react-dom'],
    input: `modules/client/${entryName}.js`,
    output: {
      format: 'iife',
      dir: 'public/_client',
      entryFileNames: '[name]-[hash].js',
      globals: {
        react: 'React',
        'react-dom': 'ReactDOM',
        '@emotion/react': 'emotionReact'
      }
    },
    moduleContext: {
      'node_modules/react-icons/lib/esm/iconBase.js': 'window'
    },
    plugins: [
      manifest.record({
        publicPath: '/_client/'
     }),
      babel({ 
        babelHelpers: 'bundled',
        exclude: /node_modules/
      }),
      json(),
      nodeResolve(),
      commonjs(),
      replace({
        preventAssignment: true,
        'process.env.BUILD_ID': JSON.stringify(buildId),
        'process.env.NODE_ENV': JSON.stringify(
          process.env.NODE_ENV || 'development'
        )
      }),
      url({
        limit: 0,
        publicPath: '/_client/'
      }),
      terser()
    ]
  };
});

const dependencies = (process.env.NODE_ENV === 'development'
  ? Object.keys(pkg.dependencies).concat(Object.keys(pkg.devDependencies || {}))
  : Object.keys(pkg.dependencies)
).concat('react-dom/server');

const server = {
  external: builtinModules.concat(dependencies),
  input: 'modules/server.js',
  output: { file: 'server.js', format: 'cjs' },
  moduleContext: {
    'node_modules/react-icons/lib/esm/iconBase.js': 'global'
  },
  plugins: [
    manifest.inject({ 
      virtualId: 'entry-manifest' 
    }),
    babel({ 
      babelHelpers: 'bundled',
      exclude: /node_modules/
    }),
    json(),
    nodeResolve(),
    commonjs(),
    url({
      limit: 0,
      publicPath: '/_client/',
      emitFiles: false
    }),
    replace({
      preventAssignment: true,
      'process.env.BUILD_ID': JSON.stringify(buildId)
    })
  ]
};
const config = client.concat(server)
export default config;
